<?php
namespace app\admin\controller\agent;

use AlibabaCloud\SDK\Ocrapi\V20210707\Ocrapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeBusinessLicenseRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Ocr  extends \app\admin\controller\Common{
    protected $noNeedRight = ['*'];
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Ocrapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => 'LTAI5tPbzf9cvgHigM25SvhB',
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => 'tWcHarLntTO5LWxOaty2R0yDca8fXZ'
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Ocrapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public  function ocr(){
        $images = '';
        $dataa = (new \app\common\controller\Upload())->image();
        $images =  $dataa['url'];
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient(getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        $recognizeBusinessLicenseRequest = new RecognizeBusinessLicenseRequest([
            "url" => $images
        ]);
        $runtime = new RuntimeOptions([]);
        $data = $client->recognizeBusinessLicenseWithOptions($recognizeBusinessLicenseRequest, $runtime);
        // try {
        //     // 复制代码运行请自行打印 API 的返回值
        //     $data = $client->recognizeBusinessLicenseWithOptions($recognizeBusinessLicenseRequest, $runtime);
        // }
        // catch (Exception $error) {
        //     if (!($error instanceof TeaError)) {
        //         $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
        //     }
        //     // 错误 message
        //     var_dump($error->message);
        //     // 诊断地址
        //     var_dump($error->data["Recommend"]);
        //     Utils::assertAsString($error->message);
        // }
        if(empty(json_decode($data->body->data,true))){
            return self::errorResult("该图片暂不支持识别");
        }
        $data = json_decode($data->body->data,true)['data'];
        return $this->successResult("",[
            'title' => $data['companyName'],
            'code' => $data['creditCode'],
            'name' => $dataa['name'],
        ]);
    }
   
}
